<template>
  <div class="name">
    <el-form
        class="name-form"
        ref="nameFormRef"
        :model="nameForm"
        :rules="nameRules"
        @submit.prevent
    >
      <el-form-item>
        <h1>Chat</h1>
      </el-form-item>
      <el-form-item class="name-input">
        <el-button
            class="submit"
            type="primary"
            @click="submitButton"
        >进入
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {defineModel, onMounted, reactive, ref} from 'vue';
import {ElMessage} from 'element-plus';
import axios from 'axios';
import {getUserProfile} from '@/apis/user.js';
import {getToken} from "@/utils/auth.js";

const selectChat = defineModel('selectChat');
const selectName = defineModel('selectName');

// 表单
const nameFormRef = ref(null);

// 用户ID
let userId = '';
let userName = '';
let avatar = '';

// 表单校验规则（目前不需要）
const nameRules = reactive({});

// 获取用户资料
const fetchUserProfile = async () => {
  try {
    const res = await getUserProfile();
    if (res.data) {
      userId = res.data.userId;
      userName = res.data.userName;
      avatar = res.data.avatar;
      sessionStorage.setItem('userId', userId);
      sessionStorage.setItem('userName', userName);
      sessionStorage.setItem('avatar', avatar);
    }
  } catch (error) {
    console.error('Failed to fetch user profile:', error);
  }
};

onMounted(() => {
  fetchUserProfile();
});


// 登录操作
const submitButton = async () => {
  if (!userId) {
    ElMessage({
      message: '无法获取用户ID，请重试',
      grouping: true,
      type: 'error',
    });
    return;
  }

  try {
    const res = await axios.get(`http://localhost:8080/list/${userId}`,
        {
          headers: {
            'Content-Type': 'application/json',
            Authorization: 'Bearer ' + getToken()
          },
        }
    );
    const data = res.data;

    // 判断用户名是否存在
    if (!data.isExist) {
      selectName.value = false;
      selectChat.value = true;
    } else {
      ElMessage({
        message: '您已经在其他地方登录了哟!',
        grouping: true,
        type: 'error',
      });
    }
  } catch (error) {
    ElMessage({
      message: '请求失败，请稍后重试',
      grouping: true,
      type: 'error',
    });
    console.error('Request failed:', error);
  }
};
</script>

<style scoped>
@import '../../assets/css/name.css';
</style>
